package com.sumer.psychology.common.domain.model;

import com.sumer.psychology.common.media.RepresentationReader;

import java.lang.reflect.Constructor;

/**
 * json转换为User
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/11/18
 * Time: 16:52
 */
public class UserTranslator {
    /**
     * 转换成User
     *
     * @param aUserInRoleRepresentation representation
     * @return user
     * @throws Exception
     */
    public User toUserFromRepresentation(
            String aUserInRoleRepresentation)
            throws Exception {
        RepresentationReader aReader = new RepresentationReader(
                aUserInRoleRepresentation);

        String identity = aReader.stringValue("user_id");
        String name = aReader.stringValue("user_lnm");
        Integer roleInt = aReader.integerValue("user_tp");

        String userName = aReader.stringValue("user_rnm");
        Integer gender = aReader.integerValue("user_male");
        String phone = aReader.stringValue("user_mobile");
        String qq = aReader.stringValue("user_qq");
        String email = aReader.stringValue("user_email");

        return newUser(identity, name, userName, gender, phone, qq, email, User.userClass(roleInt));
    }

    /*
     * 创建新的user对象
     */
    private <T extends User> T newUser(
            String identity,
            String name,
            String userName,
            int gender,
            String phone,
            String qq,
            String email,
            Class<T> aUserClass)
            throws Exception {
        Constructor<T> constructor = aUserClass.getConstructor(
                String.class,
                String.class,
                String.class,
                Integer.class,
                String.class,
                String.class,
                String.class);
        return constructor.newInstance(identity, name, userName, gender, phone, qq, email);
    }

}
